#include "strutil.h"
#include <deque>

namespace renderit
{
	namespace strutil
	{
		int int_to_str(char * outbuf, int size, int num)
		{
			char buf[10];
			int len = 0;
			int sgn = 0;
			
			// 1. is zero
			if (num == 0) {
				if (size > 0) {
					outbuf[0] = '0';
				}
				return 1;
			}

			// 2. if negative
			if (num < 0) {
				num = -num;
				sgn = 1;
			}

			while (num > 0) {
				int n = num % 10;
				buf[len++] = '0' + n;
				num /= 10;
			}

			if (len + sgn > size) {
				return len + sgn;
			}
			
			int startp = 0;
			if (sgn) {
				outbuf[startp++] = '-';
			}
			
			for (int i = len - 1; i >= 0; --i) {
				outbuf[startp++] = buf[i];
			}
			return len + sgn;
		}

		int float_to_str(char * buf, int size, double f, int fraction_cout)
		{
			int decimal = (int)f;
			if ((double)decimal == f) {
				return int_to_str(buf, size, decimal);
			}

			double fraction = f - decimal;
			if (fraction < 0) {
				fraction = -fraction;
			}

			int decimal_len = int_to_str(buf, size, decimal);
			if (decimal_len + 1 + fraction_cout > size) {
				return decimal_len + 1 + fraction_cout;
			}

			buf[decimal_len] = '.';

			for (int i = 0; i < fraction_cout; ++i) {
				fraction *= 10;
				int n = fraction;
				fraction -= n;
				buf[decimal_len + 1 + i] = '0' + n;
			}
			return decimal_len + 1 + fraction_cout;
		}
	}

}